package com.bootdo.app.service.impl;

import com.bootdo.app.common.aop.exception.ExceptionEnum;
import com.bootdo.app.common.aop.exception.MiniprogramException;
import com.bootdo.app.common.msg.Response;
import com.bootdo.app.common.utils.ContextHandlerUtil;
import com.bootdo.app.common.utils.DateUtil;
import com.bootdo.app.common.utils.WXPay;
import com.bootdo.app.dto.miniprogram.UserMeetingVipDto;
import com.bootdo.app.enums.GroupBuyingStatusEnum;
import com.bootdo.app.enums.UserMeetVipStatus;
import com.bootdo.app.service.UserGroupBuyService;
import com.bootdo.app.service.UserMeetingService;
import com.bootdo.app.vo.miniprogram.GroupBuyJoinerVo;
import com.bootdo.app.vo.miniprogram.MeetVipGoodsVo;
import com.bootdo.app.vo.miniprogram.UserMeetingVo;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.KswUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.system.domain.*;
import com.bootdo.system.dto.GmspDto;
import com.bootdo.system.dto.ProductDto;
import com.bootdo.system.mapper.*;
import com.bootdo.system.service.KswService;
import com.bootdo.system.service.OrderService;
import com.bootdo.system.service.ProductService;
import com.bootdo.system.service.UserService;
import io.swagger.models.auth.In;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.time.LocalDateTime;
import java.time.Month;

/**
 * @auther: 作者: Along
 * @description: 类说明
 * @Date: created in 2020/12/9 21:51
 */
@Slf4j
@Service
public class UserMeetingServiceImpl implements UserMeetingService{


    @Autowired
    private TbWxUserMeetingMapper userMeetingMapper;

    @Autowired
    private TbWxUserMeetVipMapper userMeetVipMapper;
    @Autowired
    private TbSvipMapper svipMapper;
    @Autowired
    private TbGroupBuyingMapper groupBuyingMapper;

    @Autowired
    private TbGroupBuyingJoinerMapper groupBuyingJoinerMapper;
    @Autowired
    private KswService kswService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserGroupBuyService userGroupBuyService;


    /**
     * 用户签到记录
     */
    @Override
    public UserMeetingVo getMeetingLog() {
        String userId = ContextHandlerUtil.getCurrentUserId();
        String date=DateUtils.format3(new Date());
        List<TbWxUserMeeting> tbWxUserMeetings = userMeetingMapper.getByUserId(Integer.valueOf(userId),date);
        List<Date> collect = tbWxUserMeetings.stream().map(m -> m.getCreateDateTime()).collect(Collectors.toList());
        UserMeetingVo vo = new UserMeetingVo();
        vo.setUserId(userId);
        vo.setMeetTime(collect);
        return vo;
    }

    /**
     * 用户签到
     */
    @Override
    public void addMeeting() {
        String currentUserId = ContextHandlerUtil.getCurrentUserId();
        String sid = ContextHandlerUtil.getSID();
        // 查询今天是否重复签到
        LocalDateTime now = LocalDateTime.now();
        String nowYear = String.valueOf(now.getYear());
        int monthValue = now.getMonthValue();
        String nowMonth = String.valueOf(monthValue);
        if(monthValue < 10){
            nowMonth = "0" + nowMonth;
        }
        int dayOfMonth = now.getDayOfMonth();
        String nowDay = String.valueOf(dayOfMonth);
        if(dayOfMonth < 10){
            nowDay = "0" + nowDay;
        }
        TbWxUserMeeting tbWxUserMeeting = userMeetingMapper.selectMeeting(Integer.valueOf(currentUserId), nowYear, nowMonth, nowDay);
        if(tbWxUserMeeting != null){
            throw new MiniprogramException(ExceptionEnum.MINI_PROGRAM_IS_MEET);
        }
        // 签到
        TbWxUserMeeting userMeeting = new TbWxUserMeeting();
        userMeeting.setSid(Integer.valueOf(sid));
        userMeeting.setWxUserId(Integer.valueOf(currentUserId));
        userMeeting.setCreateDateTime(Calendar.getInstance().getTime());
        userMeetingMapper.insert(userMeeting);
    }

    /**
     *
     * @return
     */
    @Override
    public boolean isCanGetMeetingVip() {
        final String currentUserId = ContextHandlerUtil.getCurrentUserId();
        LocalDateTime now = LocalDateTime.now();
        String nowYear = String.valueOf(now.getYear());
        int monthValue = now.getMonthValue();
        String nowMonth = String.valueOf(monthValue);
        if(monthValue < 10){
            nowMonth = "0" + nowMonth;
        }
        int meetingCount = userMeetingMapper.getMeetingCount(Integer.valueOf(currentUserId), nowYear, nowMonth);
        if(meetingCount < 20){
            throw new MiniprogramException(ExceptionEnum.MINI_PROGRAM_NOT_MEET_ENOUGH);
        }
        return true;
    }

    /**
     * 签到领会员
     * @param userMeetingVipDto
     */
    @Override
    public Response getMeetingVip(UserMeetingVipDto userMeetingVipDto) {
        Integer goodsId = userMeetingVipDto.getGoodsId();
        String phone = userMeetingVipDto.getMobile();
        if(isCanGetMeetingVip()){

            String currentUserId = ContextHandlerUtil.getCurrentUserId();
            TbWxUserMeetVip userMeetVip = new TbWxUserMeetVip();
            userMeetVip.setWxUserId(Integer.valueOf(currentUserId));
            userMeetVip.setPhone(userMeetingVipDto.getMobile());
            userMeetVip.setStatus(UserMeetVipStatus.NO_RECHARGE.getStatus());
            userMeetVip.setCreateDateTime(Calendar.getInstance().getTime());
            userMeetVip.setGoodsId(userMeetingVipDto.getGoodsId());
            userMeetVip.setGoodsType(userMeetingVipDto.getGoodsType());
            userMeetVipMapper.insertSelective(userMeetVip);
            return addVip(goodsId,phone);
        }else {
            TbGroupBuying groupBuying = groupBuyingMapper.selectByPrimaryKey(userMeetingVipDto.getGroupById());

            if (groupBuying == null) {
                return Response.fail("无法领取会员卡!");
                //return null;
            }
            Integer status = groupBuying.getStatus();
            if (!Objects.equals(status, GroupBuyingStatusEnum.MAKE.getStatus())) {
                return Response.fail("该团队以结束!");
                //return null;
            }
            Date now = Calendar.getInstance().getTime();
            if (now.compareTo(groupBuying.getEndDateTime()) > 0) { // 过期
                groupBuyingMapper.updateByPrimaryKeySelective(TbGroupBuying.updateStatus(groupBuying.getId(), GroupBuyingStatusEnum.EXPIRE.getStatus()));
                // return null;
                return Response.fail("该团队以过期!");
            }
            List<GroupBuyJoinerVo> groupBuyJoinerVos = groupBuyingJoinerMapper.selectJoiners(groupBuying.getId());
            if (groupBuyJoinerVos.size() >= 8) {
                return addVip(goodsId,phone);
            }
            // groupBuyService.list();
            return Response.fail("团队邀请人数不够!");
        }
    }

    @Override
    public List<MeetVipGoodsVo> getMeetVipGoods() {
        return svipMapper.getMeetVipGoods();
    }


    private Response addVip(Integer goodsId,String userPhone){
        String sid = ContextHandlerUtil.getSID();
        String openId = ContextHandlerUtil.getOpenId();
        String pro = WXPay.getRandomStringByLength(32);

        String customer_id=KswUtils.customer_id;
        String key=KswUtils.ksw_key;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhss");//设置日期格式
        String timestamp = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        TreeMap<String, String> treeMap = new TreeMap<String, String>();
        treeMap.put("customer_id" , customer_id);
        treeMap.put("timestamp" , timestamp);
        ProductDto gmspDto = kswService.getSpxx(goodsId, key, treeMap);
        if(gmspDto != null) {
            int stock_state = gmspDto.getStock_state();
            double price = gmspDto.getPrice();
            if(stock_state == 2) {
                return Response.fail("没有库存");
                ///return;
            }else  if(stock_state == 1) {
                TreeMap<String, String> treeMap1 = new TreeMap<String, String>();
                treeMap1.put("customer_id" , customer_id);
                treeMap1.put("timestamp" , timestamp);
                GmspDto gmspDtoz = kswService.getGmspDto(goodsId, userPhone, 1, key, treeMap1);
                TbViporder byOrdId = new TbViporder();
                byOrdId.setSid(sid);
                byOrdId.setOid(pro);
                byOrdId.setOpenid(openId);
                byOrdId.setRechargeAccount(userPhone);
                byOrdId.setQuantity("1");
                byOrdId.setTitle("购买会员卡");
                byOrdId.setDirect("0");
                byOrdId.setProductId(String.valueOf(goodsId));
                if(gmspDtoz != null) {

                    byOrdId.setStatus(2);
                    // 支付方式
                    // todo  明天此处改为微信支付订单表   更新操作
                    orderService.insert2updateSvip(byOrdId);
                    //拼团结束
                    userGroupBuyService.endGroupBuy(byOrdId.getProductId());
                }else {
                    byOrdId.setStatus(4);
                    // 支付方式
                    // todo  明天此处改为微信支付订单表   更新操作
                    orderService.insert2updateSvip(byOrdId);
                }
            }
        }else {
            return Response.fail("没有库存");
        }


        return Response.success("领取成功");

    }


    private Double getDouble2String(String num) {
        if(StringUtils.isNoneBlank(num)) {
            Double cny = Double.parseDouble(num);
            DecimalFormat df = new DecimalFormat("0.00");
            String CNY = df.format(cny);
            Double cny1 = Double.parseDouble(CNY);
            return cny1;
        }
        return 0.00;
    }

}
